//
//  RubyVC.m
//  itboye2015002
//
//  Created by pro on 15/12/29.
//  Copyright © 2015年 Boye. All rights reserved.
//

#import "RubyVC.h"

#import "RubyCell.h"


@interface RubyVC () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIView *lblEmptyMsg;
@property (nonatomic, strong) UITableView *tableView;

// 数据
@property (nonatomic, strong) NSMutableArray *unuseItems;
@property (nonatomic, strong) NSMutableArray *usedItems;

@end

@implementation RubyVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"购物券";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBarButtonItemWithImagename:nil];
    
    [self _initViews];
    
    [self _initData];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main showTabBar];
}

#pragma mark - 初始化数据 -
- (void)_initData {
    
    _usedItems = [[NSMutableArray alloc] init];
    _unuseItems = [[NSMutableArray alloc] init];
    
    [SVProgressHUD showWithStatus:@"正在加载优惠券..."];
    
    [BoyeHttpClient post:@"BY_RedEnvelope_query" apiVerson:100 params:@{@"uid":[CommonCache getUserInfo].uid} success:^(AFHTTPRequestOperation *operation, id result) {
    
        // 有红包
        if (![result isKindOfClass:[NSNull class]]) {
            
            if ([result count] == 0) {
                [self showEmpty];
            }else{
                for (NSDictionary *dic in result) {
                    RubyModel *model = [[RubyModel alloc] initContentWithDic:dic];
                    // 未使用的红包
                    if ([model.use_status intValue] == 0 && [model.expire_time intValue] + [model.get_time integerValue] > [[NSDate currentTimeStamp] intValue]) {
                        [_unuseItems addObject:model]; // 给未使用的红包数组添加一个元素
                    }
                    // 已使用或已过期的 红包
                    else {
                        [_usedItems addObject:model]; // 给已经使用的红包数组添加一个元素
                    }
                }
                [self hideEmpty];
            }
            
            // 请求好了重新刷新表视图
            [_tableView reloadData];
        } else {
            [self showEmpty];
        }
        
        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:3];
    }];
    
}
#pragma mark - 初始化视图 -
- (void)_initViews {
    [self _initTableView];
}

// 创建表视图
- (void)_initTableView {
    
    _lblEmptyMsg = [[UIView alloc] init];
    _lblEmptyMsg.frame = CGRectMake(0, 0, 120, 140);
    [self.view addSubview:_lblEmptyMsg];
    _lblEmptyMsg.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 100);
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _lblEmptyMsg.width, _lblEmptyMsg.width)];
    [imgView setContentMode:UIViewContentModeScaleAspectFill];
    imgView.image = [UIImage imageNamed:@"没有红包"];
    [_lblEmptyMsg addSubview:imgView];
    
    UILabel *notes = [[UILabel alloc]initWithFrame:CGRectMake(0, imgView.bottom, _lblEmptyMsg.width, 20)];
    notes.text = @"没有红包!";
    notes.textColor = [UIColor colorWithRGBHex:0xeb4f38];
    notes.textAlignment = NSTextAlignmentCenter;
    [_lblEmptyMsg addSubview:notes];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; // 设置没有分割线
    _tableView.showsVerticalScrollIndicator = YES;
    _lblEmptyMsg.hidden = YES;
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[RubyCell class] forCellReuseIdentifier:@"RubyCell"];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _unuseItems.count + _usedItems.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RubyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RubyCell"];
    
    // 填充数据
    if (indexPath.section < _unuseItems.count) { // 未使用的红包
        cell.model = _unuseItems[indexPath.section];
    } else { // 已使用的红包
        cell.model = _usedItems[indexPath.section - _unuseItems.count];
    }
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // 如果在个人中心查看红包则点击不需要任何操作（个人中心那里的红包没有设置代理）
    if (self.delegate == nil) {
        return;
    }
    
    if (indexPath.section < _unuseItems.count) { // 未使用的红包
        
        if ([self.delegate respondsToSelector:@selector(rubyDidChoose:)]) {
            [self.delegate rubyDidChoose:_unuseItems[indexPath.section]];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"您选择的红包已过期或已使用" withDuration:1.0];
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == _unuseItems.count) {
        return 30;
    }
    
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == _unuseItems.count) { // 过期和没过期的分界线
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        label.textColor = [UIColor grayColor];
        label.text = @"没有更多红包了";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = FONT(16);
        return label;
    }
    
    return nil;
}



- (void)showEmpty{
    _lblEmptyMsg.hidden = NO;
    _tableView.hidden = YES;
}

- (void)hideEmpty{
    _lblEmptyMsg.hidden = YES;
    _tableView.hidden = NO;
}
    
@end
